package com.example.statistics.ui.inventory

import android.os.Bundle
import android.text.method.DigitsKeyListener
import android.widget.TextView
import com.example.statistics.R
import com.example.statistics.bean.*
import com.example.statistics.common.BaseActivity
import com.example.statistics.ex.*
import com.example.statistics.net.UrlConfig
import com.example.statistics.net.callback.DataDialogHttpCallback
import com.example.statistics.ui.customer.CustomerListActivity
import com.example.statistics.utils.Constants
import com.example.statistics.utils.activityFinish
import com.example.statistics.utils.activityForResult
import com.google.gson.Gson
import com.jhj.httplibrary.HttpCall
import com.jhj.httplibrary.utils.ExtraRequestBodyUtils
import com.jhj.slimadapter.SlimAdapter
import com.example.statistics.ex.afterTextChangedListener
import com.example.statistics.ex.contentText
import kotlinx.android.synthetic.main.activity_inventory_sub.*
import kotlinx.android.synthetic.main.list_item_add.*
import kotlinx.android.synthetic.main.list_item_inventory_sales.view.*
import org.jetbrains.anko.sdk27.coroutines.onClick
import org.jetbrains.anko.toast
import java.util.*


/**
 * 出库
 */
class InventorySubActivity : BaseActivity() {

    private var datePattern = "yyyy-MM-dd HH:mm"
    private var sellerList: List<SellerBean>? = null
    private var order: InventoryOrder = InventoryOrder()
    private var seller: SellerBean? = null
    private var salesProductList = mutableListOf<InventoryProduct>()
    private var uploadUrl = ""

    override val title: String
        get() = "出库"

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_inventory_sub)
        initView()

        //获取经手人
        httpGet<List<SellerBean>>(UrlConfig.SELLER_LIST, config = {
            isShowDialog = true
        }) {
            sellerList = it
        }

        val id = intent.getIntExtra(Constants.ID, 0)
        if (id != 0) {
            httpGet<InventoryOrder>(UrlConfig.INVENTORY_SALES_DATA, config = {
                listParams = listOf("id" to id)
            }) {
                order = it ?: InventoryOrder()
                val array = order.customerName.split(" ")
                if (array.size == 2) {
                    tv_area.contentText = array[0]
                    tv_customer.contentText = array[1]
                } else if (array.size == 1) {
                    tv_customer.contentText = array[0]
                }
                tv_car.contentText = order.car
                tv_seller.contentText = order.sellerName
                val date = order.date.goTimeFormat(datePattern).orEmpty()
                tv_date.contentText = date
                order.date = date
                seller = SellerBean(order.sellerId, order.sellerName)
                order.salesProductList?.forEach { bean ->
                    salesProduct(bean)
                }
            }
            uploadUrl = UrlConfig.INVENTORY_SALES_UPDATE
        } else {
            salesProduct()
            uploadUrl = UrlConfig.INVENTORY_SALES_ADD
        }
        layout_add.onClick {
            salesProduct()
        }
    }

    fun initView() {
        tv_customer.onSymbolClicked { str ->
            activityForResult<CustomerListActivity>(
                Constants.DATA to (if (str.isNullOrBlank()) Constants.SELECTOR else str)
            ) {
                val customer = it?.getSerializableExtra(Constants.DATA) as Customer?
                val array = customer?.name.orEmpty().split(" ")
                if (array.size == 2) {
                    tv_area.contentText = array[0]
                    tv_customer.contentText = array[1]
                } else if (array.size == 1) {
                    tv_customer.contentText = array[0]
                }
                //客户的默认销售员
                if (customer?.sellerId != null) {
                    seller = sellerList?.find { sellerBean -> sellerBean.id == customer.sellerId }
                    tv_seller.contentText = seller?.sellerName.orEmpty()
                    order.sellerId = seller?.id.orEmpty()
                }
                order.customerId = customer?.ID.orEmpty()
            }
        }


        tv_seller.onContentClicked {
            singleDialog(sellerList) {
                seller = it
                order.sellerId = it.id
                tv_seller.contentText = it.sellerName
            }
        }

        order.date = Date().format(datePattern).orEmpty()
        tv_date.contentText = order.date
        tv_date.onDateClicked() {
            order.date = it
        }

        topBarRightText("保存") {
            preferenceSave(tv_date.contentText, "statisticsDate")
            if (order.customerId == 0) {
                toast("请确定顾客")
                return@topBarRightText
            }
            if (seller == null) {
                toast("请确定经历人")
                return@topBarRightText
            }
            salesProductList = salesProductList.filter {
                it.customerId = order.customerId
                it.date = order.date
                it.sellerId = order.sellerId
                it.userId = order.userId
                it.type = "销售"
                it.productId != 0 && it.salesNumber.orEmpty() > 0 && it.salesPrice.orEmpty() > 0
            }.toMutableList()
            order.type = "销售"
            order.totalAmount = salesProductList.sumEx { it.totalAmount ?: 0 }.toDouble()
            order.arrearsAmount = order.totalAmount
            order.salesProductList = salesProductList
            order.area = tv_area.contentText.orEmpty()
            order.car = tv_car.contentText.orEmpty()

            val json = Gson().toJson(order)
            val requestBody = ExtraRequestBodyUtils.upJson(json)
            HttpCall.post(uploadUrl)
                .upRequestBody(requestBody)
                .enqueue(object : DataDialogHttpCallback<InventoryOrder>(this) {
                    override fun onSuccess(data: InventoryOrder?, resultType: ResultType) {
                        toast(data?.date.orEmpty())
                        activityFinish()
                    }
                })
        }
    }

    fun adapter(): SlimAdapter {
        return slimAdapter<InventoryProduct>(R.layout.list_item_inventory_sales) {
            val tvProduct = getView<TextView>(R.id.tv_product)
            val tvNumber = getView<TextView>(R.id.tv_number)
            val tvWeight = getView<TextView>(R.id.tv_weight)
            val tvPrice = getView<TextView>(R.id.tv_price)
            val tvTotalPrice = getView<TextView>(R.id.tv_total_price)
            val tvSupplier = getView<TextView>(R.id.tv_supplier)
            val tvWarehouse = getView<TextView>(R.id.tv_warehouse)
            val tvRemark = getView<TextView>(R.id.tv_remark)
            val salesProductBean = InventoryProduct()
            var specification = 0.0

            this.clicked(R.id.tv_product) {
                activityForResult<InventoryStockListActivity>(Constants.ACTION to Constants.SELECTOR) {
                    val inventory = it?.getSerializableExtra(Constants.DATA) as InventoryBean?
                    if (inventory != null) {
                        salesProductBean.inventoryId = inventory.ID
                        salesProductBean.productId = inventory.productId
                        salesProductBean.factoryNo = inventory.factoryNo
                        salesProductBean.productName = inventory.productName
                        salesProductBean.purchaseProductId = inventory.purchaseProductId

                        tvProduct.contentText = inventory.factoryNo + inventory.productName
                        specification = getSpecification(inventory.specification)
                        if (specification == 0.0) {
                            tvWeight.keyListener = DigitsKeyListener.getInstance("0123456789")
                        } else {
                            tvWeight.keyListener = null
                            salesProductBean.salesWeight = specification.mulEx(salesProductBean.salesNumber).toDouble()
                            tvWeight.contentText = salesProductBean.salesWeight.toString()
                        }
                    }
                }
            }

            tvNumber.afterTextChangedListener { editable, _ ->

                salesProductBean.salesNumber = editable?.toString()?.toIntOrNull()
                tvWeight.contentText = specification.mulEx(salesProductBean.salesNumber).toString()
            }

            tvWeight.afterTextChangedListener { editable, _ ->
                salesProductBean.salesWeight = editable?.toString()?.toDoubleOrNull()

                val totalPrice = if (tvWeight.keyListener == null) { //定装
                    salesProductBean.salesNumber?.mulEx(salesProductBean.salesPrice)
                } else {
                    salesProductBean.salesWeight.mulEx(salesProductBean.salesPrice)
                }

                salesProductBean.totalAmount = totalPrice?.toDouble()
                tvTotalPrice.contentText = totalPrice.toString()
            }
            tvPrice.afterTextChangedListener { editable, _ ->
                salesProductBean.salesPrice = editable?.toString()?.toDoubleOrNull()
                val totalPrice = if (tvWeight.keyListener == null) { //定装
                    salesProductBean.salesNumber?.mulEx(salesProductBean.salesPrice)
                } else {
                    salesProductBean.salesWeight.mulEx(salesProductBean.salesPrice)
                }
                salesProductBean.totalAmount = totalPrice?.toDouble()
                tvTotalPrice.contentText = totalPrice.toString()
            }
            salesProductBean.supplier = tvSupplier.contentText.orEmpty()
            salesProductBean.warehouse = tvWarehouse.contentText.orEmpty()
            salesProductBean.remark = tvRemark.contentText.orEmpty()
            salesProductList.add(salesProductBean)
        }
    }


    private fun salesProduct(bean: InventoryProduct? = null) {

        var specification = 0.0
        var salesProductBean = InventoryProduct()
        val view = inflater.inflate(R.layout.list_item_inventory_sales, layout, false)
        if (bean != null) {
            salesProductBean = bean
            specification = getSpecification(bean.specification)
            view.tv_product.contentText = bean.factoryNo + bean.productName
            view.tv_weight.contentText = bean.salesWeight.toString()
            view.tv_number.contentText = bean.salesNumber.toString()
            view.tv_price.contentText = bean.salesPrice.toString()
            view.tv_total_price.contentText = bean.totalAmount.toString()
            view.tv_supplier.contentText = bean.supplier
            view.tv_warehouse.contentText = bean.warehouse
            view.tv_remark.contentText = bean.remark
            if (specification == 0.0) {
                view.tv_weight.keyListener = DigitsKeyListener.getInstance("0123456789")
            } else {
                view.tv_weight.keyListener = null
            }
        }

        view.tv_product.onContentClicked {
            activityForResult<InventoryStockListActivity>(Constants.ACTION to Constants.SELECTOR) {
                val inventory = it?.getSerializableExtra(Constants.DATA) as InventoryBean?
                if (inventory != null) {
                    salesProductBean.inventoryId = inventory.ID
                    salesProductBean.productId = inventory.productId
                    salesProductBean.factoryNo = inventory.factoryNo
                    salesProductBean.productName = inventory.productName
                    salesProductBean.purchaseProductId = inventory.purchaseProductId
                    view.tv_product.contentText = inventory.factoryNo + inventory.productName
                    specification = getSpecification(inventory.specification)
                    if (specification == 0.0) {
                        view.tv_weight.keyListener = DigitsKeyListener.getInstance("0123456789")
                    } else {
                        view.tv_weight.keyListener = null
                        salesProductBean.salesWeight = specification.mulEx(salesProductBean.salesNumber).toDouble()
                        view.tv_weight.contentText = salesProductBean.salesWeight.toString()
                    }
                }
            }
        }

        view.tv_number.afterTextChangedListener { editable, _ ->

            salesProductBean.salesNumber = editable?.toString()?.toIntOrNull()
            view.tv_weight.contentText = specification.mulEx(salesProductBean.salesNumber).toString()
        }

        view.tv_weight.afterTextChangedListener { editable, _ ->
            salesProductBean.salesWeight = editable?.toString()?.toDoubleOrNull()

            val totalPrice = if (view.tv_weight.keyListener == null) { //定装
                salesProductBean.salesNumber?.mulEx(salesProductBean.salesPrice)
            } else {
                salesProductBean.salesWeight.mulEx(salesProductBean.salesPrice)
            }

            salesProductBean.totalAmount = totalPrice?.toDouble()
            view.tv_total_price.contentText = totalPrice.toString()
        }
        view.tv_price.afterTextChangedListener { editable, _ ->
            salesProductBean.salesPrice = editable?.toString()?.toDoubleOrNull()
            val totalPrice = if (view.tv_weight.keyListener == null) { //定装
                salesProductBean.salesNumber?.mulEx(salesProductBean.salesPrice)
            } else {
                salesProductBean.salesWeight.mulEx(salesProductBean.salesPrice)
            }
            salesProductBean.totalAmount = totalPrice?.toDouble()
            view.tv_total_price.contentText = totalPrice.toString()
        }
        layout.addView(view)
        salesProductList.add(salesProductBean)
    }

    private fun getSpecification(str: String?): Double {
        val specification = str?.uppercase(Locale.getDefault())?.replace("KG", "")?.trim()
        return if (specification.isNumber())
            specification?.toDouble() ?: 0.0
        else
            0.0
    }
}